#!/bin/sh

set -eu

Tmp=build/ltgen_tmp.txt
Bak=build/ltgen_bak.txt

UpdateFromTmp() {
  cp "$1" $Bak
  mv $Tmp "$1"

  if ninja; then
    rm $Bak
  else
    echo "failed to build after re-generate $File, restore to previous version"
    mv "$Bak" "$File"
  fi
}

Main() {
  ./build.sh

  ./build/bin/ltgen collect-gens src/*.c src/*.h >$Tmp
  UpdateFromTmp src/ltgen_gens.c

  for File in src/*.c src/*.h; do
    if ! head -n1 "$File" | grep 'Use ltgen' >/dev/null; then
      continue
    fi

    ./build/bin/ltgen generate "$File" >$Tmp
    UpdateFromTmp "$File"
  done
}

Main
